<?php

namespace app\api\service\pay;

use app\common\model\AdminPaySet;

class Weixin
{
    /*微信支付配置*/
    public function SetPay($config_id = 0)
    {
        $AdminPaySet = new AdminPaySet();
        $PaySet = $AdminPaySet->where("id='" . $config_id . "'")->findOrEmpty()->toArray();
        $PaySet['config'] = json_decode($PaySet['config'], true);
        $Set = [];
        foreach ($PaySet['config'] as $k => $v) {
            $Set[$v['field']] = $v['value'];
        }
        $config = array(
            'appid' => $Set['appid'],
            'appsecret' => $Set['appsecret'],
            'mch_id' => $Set['mch_id'],
            'mch_key' => $Set['mch_key'],
            'ssl_key' => App()->getRootPath() . "public" . $PaySet['ssl_key'],
            'ssl_cer' => App()->getRootPath() . "public" . $PaySet['ssl_cert'],
        );
        return $config;
    }

    /*发起支付*/
    public function Pay($post, $config_id, $type = 'NATIVE')
    {
        $options = array(
            'body' => $post['body'],
            'out_trade_no' => $post['out_trade_no'],
            'total_fee' => $post['total_fee'] * 100,
            'trade_type' => $type,//JSAPI
            'notify_url' => $post['notify'],
            'spbill_create_ip' => '127.0.0.1'
        );
        if ($type == 'JSAPI') {
            $options['openid'] = $post['openid'];
        }
        try {
            $wechat = new \WeChat\Pay($this->SetPay($config_id));
            $result = $wechat->createOrder($options);
            if ($type == 'JSAPI') {
                $result = $wechat->createParamsForJsApi($result['prepay_id']);
            }
            return ['code' => 200, 'data' => $result, 'msg' => 'ok'];
        } catch (Exception $e) {
            return ['code' => 203, 'data' => [], 'msg' => $e->getMessage()];
        }
    }

    /*退款*/
    public function Refund($post, $config_id)
    {
        $wechat = new \WeChat\Pay($this->SetPay($config_id));
        $options = array(
            'total_fee' => $post['total_fee'] * 100,
            'refund_fee' => $post['refund_fee'] * 100,
            'sign_type' => 'MD5',
            'out_trade_no' => $post['out_trade_no'],
            'out_refund_no' => $post['out_refund_no'],
            'refund_desc' => $post['refund_desc'] ?: "无",
        );
        try {
            $result = $wechat->createRefund($options);
            if ($result['return_code'] == "SUCCESS" && $result['return_msg'] == "OK" && $result['result_code'] == "SUCCESS") {
                return ['code' => 200, 'data' => $result];
            } else {
                return ['code' => 203, 'data' => $result, 'msg' => $result['err_code_des']];
            }
        } catch (Exception $e) {
            return ['code' => 203, 'data' => [], 'msg' => $e->getMessage()];
        }
    }
}